package com.module.aichat.data


import com.common.app.data.api.ApiConstant.getBaseUrl
import com.common.app.utls.TimeUtils
import com.common.app.utls.network.interceptor.HeadUrlInterceptor
import com.common.base.data.CommonBean
import com.module.aichat.data.bean.MsgFeedbackModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import rxhttp.toAwait
import rxhttp.wrapper.param.RxHttp
import java.util.concurrent.TimeUnit

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/06/25
 *
 * 描述：
 *
 * 修订历史：
 *
 */
object AiChatApi {

//     val sendAiMsg =  "https://api.dify.ai/v1/chat-messages"//
     val SEND_AI_MSG =  getBaseUrl() +"api/v1/smart-ring/ai/chat"//

     val PROBLEM_SUGGESTIONS =  getBaseUrl() +"api/v1/smart-ring/ai/next-question"//问题建议的接口

     val MSG_FEED_BACK =  getBaseUrl() +"api/v1/smart-ring/ai/message/feedback"//消息反馈

     val STOP_AI_MSG =  getBaseUrl() +"api/v1/smart-ring/ai/chat-messages/stop"//停止聊天消息响应


     /**
      * 创建专用于SSE的OkHttpClient，不包含ResponseInterceptor
      */
     private fun createSseOkHttpClient(): OkHttpClient {
          return OkHttpClient.Builder()
               .connectTimeout(5, TimeUnit.SECONDS)
               .readTimeout(0, TimeUnit.SECONDS) // SSE需要长连接
               .writeTimeout(5, TimeUnit.SECONDS)
               .addInterceptor(HeadUrlInterceptor())// 不添加ResponseInterceptor，让错误直接传递
               .build()
     }


     /**
      * 使用toFlow方法获取SSE流
      *
      */
     fun getSseFlow(msg: String? = "",mId: Int = 0,): Flow<String> = flow {
          val response = RxHttp.postJson(SEND_AI_MSG)
//               .addHeader("Content-Type", "application/json")
//               .addHeader("Authorization","Bearer app-IFnDhnhXtCLF0mYeKhlSqnGy")
               .add("query", msg)
               .add("reply_message_id", mId)
               .add("location", "shenzhen")
               .add("local_time", TimeUtils.getTimeDateLong().toString())
               .add("user", "1")
               .add("inputs", {})
               .add("response_mode", "streaming")
               .add("auto_generate_name", true)
               .setOkClient(createSseOkHttpClient()) // 使用AI专用客户端
               .execute()

          // 手动检查状态码
          if (response.code != 200) {
               throw Exception("Server error: ${response.code} ${response.message}")
          }

          response.body?.source()?.use { source ->
               while (!source.exhausted()) {
                    source.readUtf8Line()?.let { line ->
                         if (line.startsWith("data: ")) {
                              emit(line.substring(6))
                         }
                    }
               }
          }
     }.flowOn(Dispatchers.IO)

     suspend fun getProblemSuggestions() =
          withContext(Dispatchers.IO) {
               RxHttp.get(PROBLEM_SUGGESTIONS)
                    .toAwait<CommonBean<List<String>>>()
                    .await()
          }

     suspend fun requestMsgFeedback(msgId:String, rating:String) =
          withContext(Dispatchers.IO) {
               RxHttp.postJson(MSG_FEED_BACK)
                    .add("message_id",msgId)
                    .add("rating",rating)
                    .toAwait<CommonBean<MsgFeedbackModel>>()
                    .await()
          }

     suspend fun requestStopAiMsg() =
          withContext(Dispatchers.IO) {
               RxHttp.postJson(STOP_AI_MSG)
                    .toAwait<CommonBean<Any>>()
                    .await()
          }

}